package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!s.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

/**
 * @param employeeDTO:
 * @return void
 * @author SunGang
 * @description 添加员工
 * @date 2023/12/3 15:10
 */
    @Override
    public void create(EmployeeDTO employeeDTO) {
        check(employeeDTO);

        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.insert(employee);
    }
/**
 * @param employeePageQueryDTO:
 * @return PageResult
 * @author SunGang
 * @description 员工分页查询
 * @date 2023/12/3 15:09
 */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Employee employeequery = new Employee();
        employeequery.setName(employeePageQueryDTO.getName());
        Page<Employee> employees = employeeMapper.selectByName(employeequery);
        long total = employees.getTotal();
        List<Employee> employeeList = employees.getResult();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(employeeList);

        return pageResult;
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.updateStatusById(employee);
    }

    @Override
    public Employee queryById(Long id) {
     Employee employee=  employeeMapper.selectById(id);
     employee.setPassword(null);
     return  employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        check(employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.updateStatusById(employee);
    }



    /**
 * @param employeeDTO:
 * @return void
 * @author SunGang
 * @description 添加员工数据校验实现
 * @date 2023/12/3 15:09
 */
    private void check(EmployeeDTO employeeDTO) {
        //账号输入不符请输入3-20个字符
        if (Objects.isNull(employeeDTO.getUsername()) ||
                employeeDTO.getUsername().length() < 3 || employeeDTO.getUsername().length() > 20) {
            throw new AccountFomatException("账号输入不符请输入3-20个字符");
        }
        //请输入正确的手机号  11位
        if (Objects.isNull(employeeDTO.getPhone()) ||
                employeeDTO.getPhone().length() != 11) {
            throw new PhoneFomatException("请输入正确的手机号");
        }
        //身份证号码不正确 18位
        if (Objects.isNull(employeeDTO.getIdNumber()) ||
                employeeDTO.getIdNumber().length() != 18) {
            throw new AccountException("身份证号码不正确");
        }
        //账号重复,请调整
        Integer countByUsername=0;
        if(Objects.isNull(employeeDTO.getId())){
            countByUsername = employeeMapper.selectCountByUsername(employeeDTO.getUsername());
        }else{
            countByUsername = employeeMapper.selectCountByUsernameIdNotSelf(employeeDTO.getUsername(),employeeDTO.getId());
        }

        if (countByUsername > 0) {
            throw new AccountRepectException("账号重复,请调整");
        }
    }
}
